// derived from SUN's examples in the javax.comm package
package javaapplication3;

import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
import gnu.io.*; // for rxtxSerial library

import oracle.jdbc.pool.OracleDataSource;
import java.sql.*;

public class nulltest implements Runnable, SerialPortEventListener {

    static CommPortIdentifier portId;
    static CommPortIdentifier saveportId;
    static Enumeration portList;
    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    static ResultSet rs;
    static OracleDataSource ods;
    static Connection con;
    static Statement s;
    static String messageString;
    static OutputStream outputStream;
    static boolean outputBufferEmptyFlag = false;
    int RS = 0;//, R = 0;

    public static void main(String[] args) {


        String Q = "insert into WSN values(1,55,3,3,sysdate)";
        String Q1 = "select * from com where nod_id=1";
        try {
            ods = new OracleDataSource();
            ods.setURL("jdbc:oracle:thin:hr/hr@localhost:1521/XE");
            con = ods.getConnection();
            s = con.createStatement();


        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO code application logic here
        boolean portFound = false;
        String defaultPort;

        // determine the name of the serial port on several operating systems
        String osname = System.getProperty("os.name", "").toLowerCase();
        if (osname.startsWith("windows")) {
            // windows
            defaultPort = "COM1";
        } else if (osname.startsWith("linux")) {
            // linux
            defaultPort = "/dev/ttyS0";
        } else if (osname.startsWith("mac")) {
            // mac
            defaultPort = "????";
        } else {
            System.out.println("Sorry, your operating system is not supported");
            return;
        }

        if (args.length > 0) {
            defaultPort = args[0];
        }

        System.out.println("Set default port to " + defaultPort);

        // parse ports and if the default port is found, initialized the reader
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(defaultPort)) {
                    System.out.println("Found port: " + defaultPort);
                    portFound = true;
                    // init reader thread
                    nulltest reader = new nulltest();
                }
            }

        }
        if (!portFound) {
            System.out.println("port " + defaultPort + " not found.");
        }

    }

    public void initwritetoport() {
        // initwritetoport() assumes that the port has already been opened and
        //    initialized by "public nulltest()"

        try {
            // get the outputstream
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
        }

        try {
            // activate the OUTPUT_BUFFER_EMPTY notifier
            serialPort.notifyOnOutputEmpty(true);
        } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
        }

    }

    public void writetoport() {


        System.out.println("Writing \"" + messageString + "\" to 0x0E" + serialPort.getName());
        try {
            // write string to serial port
            outputStream.write(messageString.getBytes());
        } catch (IOException e) {
        }
    }

    public nulltest() {
        // initalize serial port
        try {
            serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
        } catch (PortInUseException e) {e.printStackTrace();
        }

        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
        }

        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
        }

        // activate the DATA_AVAILABLE notifier
        serialPort.notifyOnDataAvailable(true);

        try {
            // set port parameters
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
        }

        // start the read thread
        readThread = new Thread(this);
        readThread.start();

    }

    public void run() {

        // first thing in the thread, we initialize the write operation
        initwritetoport();
        try {
            while (true) {
                String query = "select r,s from com  where nod_id=1";
                try {
                    s.execute(query);
                    rs = s.getResultSet();
                    rs.next();
                    RS = Integer.parseInt(rs.getString("s"));
                //    R = Integer.parseInt(rs.getString("r"));
                    System.out.println(RS);
                } catch (Exception e) {
                }
                // write string to port, the serialEvent will read it
                

                    messageString = Integer.toString(RS);
                    writetoport();
                
                Thread.sleep(2000);
            }
        } catch (InterruptedException e) {
        }
    }

    public void serialEvent(SerialPortEvent event) {



        int num = 0;
        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
                break;
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                System.out.print("buffer is full \n");
                break;

            case SerialPortEvent.DATA_AVAILABLE:
                if (RS == 1) {
                    // we get here if data has been received
                    byte[] readBuffer = new byte[20];
                    int x = -1;
                    int h = 0, t = 0, v = 0;
                    try {
                        //x =inputStream.read(readBuffer);
                        // read data
                        //while (inputStream.available() > 0) {
                        x = inputStream.read(readBuffer);

                        //while(x>0)
                        //{
                        //   inputStream.read(readBuffer);
                        //}

                        //System.out.print(x);
                        //}
                        // rs= s.getResultSet();
                        // int num =0;
                        //if(rs.next())
                        //num =Integer.parseInt(rs.getString("ms

                        String result = new String(readBuffer);


                        String output = "";
                        int i;
                        for (i = 0; i < 20; ++i) {
                            
                            if (readBuffer[i] == 'T') {
                                output += "Temprature =" + (int) readBuffer[i + 1] + "\n";
                                t = (int) readBuffer[i + 1];
                            }
                            if (readBuffer[i] == 'H') {
                                output += "Humidity =" + (int) readBuffer[i + 1] + "\n";
                                h = (int) readBuffer[i + 1];
                            }
                            if (readBuffer[i] == 'V') {
                                output += "Voltage =" + (int) readBuffer[i + 1] + "\n";
                                v = (int) readBuffer[i + 1];
                            }

                        }
                        if (!output.equals("")) {
                            String q1 = "select max(num) as ms from wsn";
                            try {
                                s.execute(q1);
                                rs = s.getResultSet();

                                if (rs.next()) {
                                    num = Integer.parseInt(rs.getString("ms"));
                                          }
                            } catch (Exception e) {  }
                            // print data
                            //   if ((int) readBuffer[0] != -1) {
                            String q = "insert into wsn values("+ ++num+","+1+","+t+","+h+","+v+","+"sysdate"+")";
                            try {
                                s.execute(q);
                            } 
                            catch (Exception e) {
                            }

                            System.out.println(output);
                        }


                    // }
                    } catch (IOException e) {
                    }

                    break;
                }



        }
    }
}
